package com.sto.stoapp.md5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5
 * @author hb
 *
 */
public class Md5 {
	private final static char[] BCD_LOOKUP = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public final static String bytesToHexStr(byte[] bcd) {
		StringBuilder sb = new StringBuilder(bcd.length * 2);

		for (int i = 0; i < bcd.length; i++) {
			sb.append(BCD_LOOKUP[(bcd[i] >>> 4) & 0x0f]);
			sb.append(BCD_LOOKUP[bcd[i] & 0x0f]);
		}

		return sb.toString();
	}

	public static String getMD5Hex(String src) {

		byte[] b = getMD5Digest(src.getBytes());
		return bytesToHexStr(b);
	}

	public static byte[] getMD5Digest(byte[] bsrc) {
		try {
			MessageDigest alg = MessageDigest.getInstance("MD5");
			alg.update(bsrc);
			return alg.digest();
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

}
